package com.spz.demo.singleboot.shiro.realm;

import com.spz.demo.singleboot.common.SysConst;
import com.spz.demo.singleboot.entity.User;
import com.spz.demo.singleboot.service.UserService;
import com.spz.demo.singleboot.shiro.token.UserAuthenticationToken;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

/**
 *
 * 用来给shiro注入认证信息和授权信息
 */
@Slf4j//(topic = "USER_LOG")
@Component("userRealm")
public class UserRealm extends AuthorizingRealm{

    @Autowired
    private UserService userService;
    @Value("${jwt.salt}")
    private String jwtSalt;

    private static final String DEFAULT_JWT_SALT = "asdfh2738yWsdjDfha";//默认的盐

    /**
     * 授权处理
     * 不使用
     * @param principals
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        return null;
    }

    /**
     * 身份认证
     *
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        // 获取用户
        String account = (String) authenticationToken.getPrincipal();//这里的user里只有账号和未加密的密码
        User user = userService.getUserByAccount(
                account,
                SysConst.ENABLE_YES,
                SysConst.DEL_NO);
        if (user  == null) {
            return null;
        }else{
            ((UserAuthenticationToken)authenticationToken).setUserId(user.getId());//赋值userId
        }

        return new SimpleAuthenticationInfo(
                user,
                user.getPassword().toCharArray(),
                ByteSource.Util.bytes((jwtSalt == null ? DEFAULT_JWT_SALT: jwtSalt)),//盐
                getName()
        );
    }
}